﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;

namespace Acid.GraphBuilder.Code
{
    public class Device2D : IDisposable
    {
        private Control  control;
        private Graphics graphics0;
        private Graphics graphics1;
        private Bitmap   bitmap;

        public Device2D(Control control)
        {
            this.control         = control;
            this.bitmap          = new Bitmap(this.control.ClientRectangle.Width, this.control.ClientRectangle.Height);
            this.graphics0       = Graphics.FromImage(this.bitmap);
            this.graphics1       = this.control.CreateGraphics();
            this.control.Resize += new EventHandler(control_Resize);
        }

        public void DrawRectangle(Point position, int width, int height)
        {
            this
        }

        public void Clear(Color color)
        {
            this.graphics0.Clear(color);
        }

        public void Present()
        {
            this.graphics1.DrawImage(this.bitmap, new Rectangle(0, 0, this.control.ClientRectangle.Width, this.control.ClientRectangle.Height));
        }

        #region Events

        private void control_Resize(object sender, EventArgs e)
        {
            this.graphics1.Dispose();

            this.graphics0.Dispose();
            
            this.bitmap.Dispose();

            this.graphics1 = this.control.CreateGraphics();

            this.bitmap    = new Bitmap(this.control.ClientRectangle.Width, this.control.ClientRectangle.Height);
            
            this.graphics0 = Graphics.FromImage(this.bitmap);
        }

        #endregion

        #region IDisposable Members

        private bool disposed = false;

        private void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (!disposed)
                {
                    this.graphics0.Dispose();
                    this.graphics1.Dispose();
                    this.bitmap.Dispose();
                    this.disposed = true;
                }
            }
        }

        public void Dispose()
        {
            this.Dispose(true);
        }

        ~Device2D()
        {
            this.Dispose(false);
        }

        #endregion
    }
}
